import { Inject, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

import { type IConfiguration } from '../config/configuration';
import { DataFactory } from '../core/common/global/dataFactory/dataFactory.service';
import { type IPlatform } from '../interface.d';
import { fullScreenChrome } from '../utils';

@Injectable()
export class ApiService {
  private readonly logger = new Logger(ApiService.name);

  @Inject(ConfigService)
  private configService: ConfigService<IConfiguration>;

  @Inject()
  private globalService: DataFactory;

  getConfig(key: `${number}${number}` | `${number}${number}${number}`) {
    console.log('AT-[ key &&&&&********** ]', key);
  }

  async openBrowser(folder: string, platform: IPlatform) {
    const rules = await this.globalService.createBaseData();
    // const rules = await this.globalService.createBaseDataNew();

    const findResult = rules.find(i => i.folder == folder && i.platforms.includes(platform));

    if (!findResult) {
      this.logger.error(`${folder} 找不到对应的 ${platform}`);
      return;
    }

    const { ip, cacheDirName } = findResult;

    this.globalService.setIp(ip);

    const browser = await this.globalService.createBroswer(cacheDirName);

    const [page] = await browser.pages();

    const urlMaps = new Map([
      ['bili', 'https://member.bilibili.com/'],
      ['xhs', 'https://creator.xiaohongshu.com/login'],
      ['douyin', 'https://creator.douyin.com/'],
    ]);

    await page.setRequestInterception(true);
    page.on('request', interceptedRequest => {
      if (interceptedRequest.isInterceptResolutionHandled()) return;

      const url = interceptedRequest.url();

      if (url.endsWith('.png') || url.endsWith('.jpg') || url.endsWith('output.mp4')) interceptedRequest.abort();
      else interceptedRequest.continue();
    });

    await page.goto(urlMaps.get(platform));

    fullScreenChrome();
  }
}
